﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace PTViewer
{
    public partial class ViewThreadForm : Form
    {
        public ViewThreadForm()
        {
            InitializeComponent();
        }
        public ViewThreadForm(string url)
        {
            InitializeComponent();
            Directory.CreateDirectory("files");
            BindGrid(url);

        }

        private void BindGrid(string url)
        {
            var ind = url.IndexOf("tid") + 4;
            var tid = url.Substring(ind, url.Length - ind);
            var fpath = string.Format("files/{0}.html", tid);
            string html = "";
            bool needDown = true;
            if (!File.Exists(fpath) || needDown)
            {
                html = new Helper().DownloadWebPage(url);
                File.WriteAllText(fpath, html, Encoding.UTF8);

            }
            else
            {
                html = File.ReadAllText(fpath);
            }

            FillGrid(html);
        }



        private void FillGrid(string html)
        {
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            var tables = doc.DocumentNode
                .SelectNodes("//table[@class='msgTable']");

            dataGridView1.Rows.Clear();

            foreach (var tt in tables)
            {

                var msg = tt.ChildNodes[3].ChildNodes[3];
                var td1 = msg.InnerText;
                //user info
                var userInfo = tt.ChildNodes[3].ChildNodes[1];
                dataGridView1.Rows.Add(new[] { td1, userInfo.InnerText });

            }
        }
    }
}
